var http = require("http"); //HTTP Server
var url = require("url"); // URL Handling
var fs = require('fs'); // Filesystem Access (writing files)
var sys = require('sys')

var express = require('express'), //App Framework (similar to web.py abstraction)
    app = express.createServer();
	app.use(express.bodyParser());
	app.use(app.router);
	
	
	
// http://nodejs.org/api.html#_child_processes
var exec = require('child_process').exec;
var child;



app.get('/', function(req, res){
	indexer = fs.readFileSync('index.html').toString()
    res.send(indexer);
});

db_connected = false
try
{
	var mongo = require('mongoskin');
	var db = mongo.db("localhost:27017/enviromental_data")
	db_connected = true
}
catch (err)
{
	console.log(err)
}

/*
parseCsvFile('ccny.csv', function(rec){
	
	out = {}
	out['time'] = rec.time*1000
	var data='P:'+rec.load 
	parts = data.trim().split(",")
	for (var i = 0; i < parts.length; i++)
	{
		darts = parts[i].split(":")
		out[darts[0]] = parseInt(darts[1])
	}
	console.log(out)
	//if (db_connected)
	//{
	//	db.collection("load").insert(out)
	//}

	
  sys.puts("record: " + rec.time + " " + rec.load)
});
*/

app.listen(4001);
console.log('Express server started on port');

data_log = []

function saveData() {
	out = {}
	out['time'] = new Date().getTime()
	var data='H:49,T:67,L1:89,L2:22' 
	parts = data.trim().split(",")
	for (var i = 0; i < parts.length; i++)
	{
		darts = parts[i].split(":")
		out[darts[0]] = parseInt(darts[1])
	}
	console.log(out)
	if (db_connected)
	{
		db.collection("longball").insert(out)
		db.collection("shortball").insert(out)
	}
	
}

setInterval(function() {
	// executes `pwd`
	child = exec("/usr/bin/python ./p1.sh", function (error, stdout, stderr) {
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (error !== null) {
			console.log('exec error: ' + error);
		}
	});
		
	},5000)
	
	
	function parseCsvFile(fileName, callback){
	  var stream = fs.createReadStream(fileName)
	  var iteration = 0, header = [], buffer = ""
	  var pattern = /(?:^|,)("(?:[^"]+)*"|[^,]*)/g
	  stream.addListener('data', function(data){
	    buffer+=data.toString()
	    var parts = buffer.split('\r')
	    parts.forEach(function(d, i){
	      if(i == parts.length-1) return
	      if(iteration++ == 0 && i == 0){
	        header = d.split(pattern)
	      }else{
	        callback(buildRecord(d))
	      }
	    })
	    buffer = parts[parts.length-1]
	  })

	  function buildRecord(str){
	    var record = {}
	    str.split(pattern).forEach(function(value, index){
	      if(header[index] != '')
	        record[header[index].toLowerCase()] = value.replace(/"/g, '')
	    })
	    return record
	  }
	}
